<script setup>
import {ref, onMounted, computed} from 'vue'
import { sessionApi, pageFileApi, updNameApi, updTypeApi, delFilesApi, treeTypeApi, oneFileApi } from '@/common/api'
import router from '@/common/router'
import Note from '@/components/notify'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import { CScrollbar } from 'c-scrollbar'
import Pager from '@/components/pagination/UbtPager.vue'
import { formatDate } from '@/common/filter'
import UbtTreeSel from '@/components/cascader/UbtTreeSel.vue'
import UbtSelect from '@/components/select/UbtSelect.vue'
import axios from 'axios'
import filePic from '@/assets/img/4.png'

// 自动加载，判断权限
onMounted(() => {
  checkAuth()
})

const procAuth = ref({
  addAuth: false,
  delAuth: false,
  edtAuth: false,
  typAuth: false
})
// checkAuth 获取权限
const checkAuth = async () => {
  const res = await sessionApi()
  if (res.code === 200) {
    const userBtnCode = res.data.btnCodes
    procAuth.value = {
      addAuth: userBtnCode.indexOf('1001020201') !== -1,
      delAuth: userBtnCode.indexOf('1001020202') !== -1,
      edtAuth: userBtnCode.indexOf('1001020203') !== -1,
      typAuth: userBtnCode.indexOf('1001020204') !== -1
    }
    list(0, 1)
    selType()
  } else {
    Msg({ kind: 'error', txt: res.msg })
    router.replace('/login')
  }
}

const schObj = {
  schName: '',
  fileType: '',
  typeName: '',
  typeCode: '',
  kind: 0,
  kindName: '',
  kindCode: '',
  beginTime: 0,
  endTime: 0,
  offset: 0,
  limit: 28
}
const kindList = ref([
  {selId: 1, selName: '图片', selCode: '101', chked: false},
  {selId: 2, selName: '文档', selCode: '102', chked: false},
  {selId: 3, selName: '压缩包', selCode: '103', chked: false},
  {selId: 4, selName: '音视频', selCode: '104', chked: false},
  {selId: 5, selName: '其它', selCode: '105', chked: false}
])
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const fileList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageFileApi(schRef.value)
  if(res.code === 200 && res.data) {
    hasData.value = true
    total.value = res.data.total
    fileList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    schName: '',
    fileType: '',
    typeName: '',
    typeCode: '',
    kind: 0,
    kindName: '',
    kindCode: '',
    beginTime: 0,
    endTime: 0,
    offset: 0,
    limit: 28
  }
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    fileList.value.forEach(item => {
      idList.value.push(item.fileId)
      checkList.value.push(true)
    })
  } else {
    fileList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, fileId) => {
  if(!checkList.value[idx]) {
    idList.value.push(fileId)
  } else {
    const index = idList.value.findIndex(id => {
      if (id === fileId) {
        return true
      }
    })
    idList.value.splice(index, 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const fileObj = {
  fileIds: '',
  fileType: '',
  typeName: '',
  fileId: '',
  fileName: ''
}
const fileForm = ref(fileObj)
// updType 批量修改分类
const modalShow1 = ref(false)
const modalShow2 = ref(false)
const modalShow3 = ref(false)
const updType = () => {
  if(idList.value.length > 0) {
    modalShow1.value = true
  } else {
    Msg({ kind: 'warn', txt: '请至少选择一项进行修改！' })
  }
}

// updTypeProc 修改分类提交提交
const updTypeProc = async () => {
  let fileIds = idList.value.join(",")
  let fileType = fileForm.value.fileType
  if(fileIds === '' || fileIds.length < 21) {
    Msg({ kind: 'warn', txt: '请至少选择一项进行修改！' })
    return
  } else if(fileType === '' || fileType.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择要迁移到的分类！' })
    return
  }
  fileForm.value.fileIds = fileIds
  const res = await updTypeApi(fileForm.value)
  if(res.code === 200) {
    closeModal(1)
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，文件分类修改成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// updName 修改名称
const updName = (fileId, fileName) => {
  modalShow2.value = true
  fileForm.value.fileId = fileId
  fileForm.value.fileName = fileName
}

// updNameProc 修改文件名称提交
const updNameProc = async () => {
  let fileId = fileForm.value.fileId
  let fileName = fileForm.value.fileName
  if(fileId === '' || fileId.length !== 21) {
    Msg({ kind: 'warn', txt: '文件编号不能为空！' })
    return
  } else if(fileName === '' || fileName.length ===0 || fileName.length > 85) {
    Msg({ kind: 'warn', txt: '文件名称不能为空，且不超过80个字符！' })
    return
  }
  const res = await updNameApi(fileForm.value)
  if(res.code === 200) {
    closeModal(2)
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，文件名称修改成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = (kind) => {
  switch(kind) {
    case 1:
      modalShow1.value = false
      fileForm.value.fileType = ''
      fileForm.value.typeName = ''
      fileForm.value.typeCode = ''
      break;
    case 2:
      modalShow2.value = false
      fileForm.value.fileId = ''
      fileForm.value.fileName = ''
      break;
    case 3:
      modalShow3.value = false
      break;
  }
}

// deletes 删除文件
const deletes = async() => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('确定要删除选中的文件吗？').then(() => {
    delFiles()
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// delFiles 删除文件实现，分离出来防止调用时异步报错
const delFiles = async () => {
  let fileIds = idList.value.join(',')
  const res = await delFilesApi({ fileIds })
  if(res.code === 200) {
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，文件信息删除成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time, kind) => {
    let date = new Date(time*1000)
    return formatDate(date, kind)
  }
})

// selType 获取分类下拉列表
const typeList = ref([])
const selType = async () => {
  const res = await treeTypeApi({kind: 2})
  if(res.code === 200) {
    typeList.value = res.data
  }
}

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.fileType = item.selId
      schRef.value.typeName = item.selName
      schRef.value.typeCode = item.selCode
      break
    case 2:
      fileForm.value.fileType = item.selId
      fileForm.value.typeName = item.selName
      fileForm.value.typeCode = item.selCode
      break
    case 3:
      schRef.value.kind = item.selId
      schRef.value.kindName = item.selName
      schRef.value.kindCode = item.selCode
      break
  }
}

// detailFile 查看文件详情
const fileRef = ref()
const detailFile = async (fileId) => {
  const res = await oneFileApi({fileId})
  if(res.code === 200) {
    modalShow3.value = true
    fileRef.value = res.data
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// download 下载文件
const download = async (fileId) => {
  axios.post('http://api-rbac.nas.com/system/file/download', {fileId}, {
  // axios.post('http://127.0.0.1:8101/system/file/download', {fileId}, {
    headers: {'token': localStorage.getItem("token")},
    responseType: 'blob'
  }).then(res => {
    let aTag = document.createElement("a")
    aTag.href = window.URL.createObjectURL(new Blob([res.data]))
    aTag.download = decodeURI(res.headers['content-disposition'].split('=')[1].replace(' ', ''))
    aTag.click()
    window.URL.revokeObjectURL(aTag.href)
  }).catch(function (err) {
    Msg({kind: 'error', txt: err})
  })
}
</script>

<template>
  <div class="a">
    <!-- 头部文件 -->
    <div class="b">
      <div class="c"><i @click="checkAll()" :class="['iconfont', allCheck ? 'checkmark_square_fill chked' : 'app chk']"></i></div>
      <div v-if="procAuth.typAuth" class="btn-p" title="批量修改文件分类" @click="updType()"><i class="iconfont doc_text"></i> 迁移</div>
      <div v-if="procAuth.delAuth" class="btn-d" title="删除" @click="deletes()"><i class="iconfont trash"></i> 删除</div>
      <div class="btn-r" title="筛选" @click="search()"><i class="iconfont search"></i></div>
      <div class="btn-r" title="刷新" @click="list(0, 1)"><i class="iconfont arrow__circlepath"></i></div>
    </div>
    <!-- 中部数据 -->
    <div class="d" v-if="schShow">
      <div class="e"><ubt-tree-sel :kind="1" :tree-list="typeList" :inboxed="true" :curName="schRef.typeName!=='' ? schRef.typeName+'['+schRef.typeCode+']' : ''" pre-name="分类" @setValue="setValue" /></div>
      <div class="e"><ubt-select :kind="3" :sel-list="kindList" :inboxed="true" :curName="schRef.kindName!=='' ? schRef.kindName+'['+schRef.kindCode+']' : ''" pre-name="种类" @setValue="setValue" /></div>
      <div class="e"><input type="text" v-model="schRef.schName" placeholder="请输入名称或编码的关键字" class="f" /></div>
      <div class="btn-p" @click="list(0, 1)"><i class="iconfont search"></i> 筛选</div>
      <div class="btn-d" @click="clrSch()"><i class="iconfont arrowshape_turn_up_left"></i> 重置</div>
    </div>
    <div class="g" v-if="hasData">
      <div class="h">
        <div class="i" v-for="(curFile, index) in fileList" :key="curFile.fileId">
          <div class="j" @click="detailFile(curFile.fileId)"><img :alt="curFile.fileName+curFile.fileExt" :src="curFile.kind===1 ? curFile.visitUrl.replace('/img/', '/img/thumb/') : filePic" class="max-img" /></div>
          <div class="k">{{curFile.fileName}}</div>
          <div class="l">
            <div class="m"><i @click="checkCurId(index, curFile.fileId)" :class="['iconfont', checkList[index] ? 'checkmark_square_fill chked' : 'app chk']"></i></div>
            <div v-if="procAuth.edtAuth" class="m"><span class="cl-blue" title="修改文件名称" @click="updName(curFile.fileId, curFile.fileName)"><i class="iconfont square_pencil"></i> 改名</span></div>
          </div>
        </div>
      </div>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 修改文件分类 -->
    <transition name="fade-mod" appear>
      <div v-if="modalShow1" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 400px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_text fs20"></i> 修改文件分类</div>
              <div class="header-right" @click="closeModal(1)"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>文件分类</div>
                <ubt-tree-sel :tree-list="typeList" :kind="2" :inboxed="false" :curName="fileForm.typeName ? fileForm.typeName+'['+fileForm.typeCode+']' : ''" pre-name="所属分类" @setValue="setValue" />
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="updTypeProc()"><i class="iconfont today_fill"></i> 保存</div>
              <div class="btn-d" @click="closeModal(1)"><i class="iconfont arrowshape_turn_up_left"></i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>

    <!-- 修改文件名称 -->
    <transition name="fade-mod" appear>
      <div v-if="modalShow2" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 800px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_text fs20"></i> 修改文件名称</div>
              <div class="header-right" @click="closeModal(2)"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>文件名称</div>
                <div><input type="text" v-model="fileForm.fileName" placeholder="请选输入文件名称" class="txt" /></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="updNameProc()"><i class="iconfont today_fill"></i> 保存</div>
              <div class="btn-d" @click="closeModal(2)"><i class="iconfont arrowshape_turn_up_left"></i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>

    <!-- 查看文件详情 -->
    <transition name="fade-mod" appear>
      <div v-if="modalShow3" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 1100px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_text fs20"></i> 查看文件详情</div>
              <div class="header-right" @click="closeModal(3)"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div class="n">
                <div class="o">
                  <div class="ipt-title">文件名称</div>
                  <div class="p">{{fileRef.fileName}}{{fileRef.fileExt}}</div>
                </div>
                <div class="o">
                  <div class="ipt-title">文件大小</div>
                  <div class="p">{{parseInt(fileRef.fileSize/1024)}}kb</div>
                </div>
                <div class="o">
                  <div class="ipt-title">文件分类</div>
                  <div class="p">{{fileRef.typeName}}[{{fileRef.typeCode}}]</div>
                </div>
                <div class="o">
                  <div class="ipt-title">上传时间</div>
                  <div class="p">{{fmtDate(fileRef.addTime, 2)}}</div>
                </div>
              </div>
              <div v-if="fileRef.kind===1" class="q"><img :alt="fileRef.fileName" :src="fileRef.visitUrl" class="max-img" /></div>
              <div v-else class="btn-p" @click="download(fileRef.fileId)">下载</div>
            </div>
            <div class="modal-footer">
              <div class="btn-d" @click="closeModal(3)"><i class="iconfont arrowshape_turn_up_left"></i> 关闭</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.a {width: 100%; height: 100%;}
.b {padding: 10px 20px; display: flex; display: -webkit-flex;}
.c {margin: 5px 15px 0 0;}
.d {margin: 0 10px 10px 10px; border: 1px solid #CCC; display: flex; display: -webkit-flex; padding: 15px; flex-wrap: wrap; justify-content: flex-end;}
.e {flex-grow: 1; margin-bottom: 15px;}
.f {width: 230px; padding: 8px;}
.g {background-color: #FFF;}
.h {display: flex; display: -webkit-flex; flex-wrap: wrap; padding: 5px;}
.i {width: 154px; height: 214px; border: 1px #EBEBEB solid; padding: 0 5px; margin: 5px;}
.i:hover {box-shadow: #CCC 0 0 5px;}
.j {width: 150px; height: 150px; overflow: hidden; padding: 2px; text-align: center; cursor: pointer; display: flex; align-items: center; justify-content: center;}
.k {height: 30px; text-align: center;}
.l {text-align: center; display: inline-flex; display: -webkit-inline-flex; justify-content: space-around; flex-direction: row;}
.m {width: 60px;}
.n {display: flex; display: -webkit-flex; flex-wrap: wrap; padding:20px;}
.o {width: 50%;}
.p {padding: 5px 20px;}
.q {border: 1px solid #CCC; padding: 4px; text-align: center;}
</style>
